<template>
  <div>
    <!-- 审核 -->
    <el-dialog
      v-el-drag-dialog
      :title="'审核--' + temp.depositCode"
      :visible.sync="visible"
      append-to-body
      width="80%"
      @closed="reset"
    >
      <div class="dialog-main">
        <div class="main-left">
          <el-form ref="dataForm" class="form" :rules="rules" :model="params" label-width="100px" label-position="right">
            <el-row :gutter="16" class="row-box">
              <el-col :span="12">
                <el-form-item label="押金单号">
                  <el-input v-model="temp.depositCode" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户姓名">
                  <el-input v-model="temp.csmName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号">
                  <el-input v-model="temp.csmCardNo" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话">
                  <el-input v-model="temp.csmPhone" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="详细地址">
                  <el-input v-model="temp.csmAddress" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label-width="0">
                  <lb-table
                    ref="lbTable"
                    border
                    highlight-current-row
                    element-loading-text="加载中"
                    :column="tableData.column"
                    :data="tableData.data.rows"
                    :pagination="false"
                    :summary-method="getSummaries"
                    show-summary
                    align="center"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label-width="100px" label="备  注">
                  <el-input v-model="temp.remark" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开始时间">
                  <el-input v-model="beginDt" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="审核时间" prop="atTime">
                  <el-date-picker
                    v-model="params.atTime"
                    type="datetime"
                    disabled
                    format="yyyy-MM-dd HH:mm:ss"
                    :clearable="false"
                    placeholder="选择日期"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手续费">
                  <el-input v-model="fee1" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="经办时间">
                  <el-input v-model="transactDt" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="经办人">
                  <el-input v-model="temp.transactor" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="押瓶机构">
                  <el-input v-model="temp.ckOrgName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收款人">
                  <el-input v-model="temp.depReceiver" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收款方式">
                  <el-input v-model="calcType" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收据单号">
                  <el-input v-model="temp.billCode" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="支付方式">
                  <el-input v-model="paymentMethod" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="支付状态">
                  <el-input v-model="payStatus" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div style="color: red;">
            特别提示:【审核时间】即入账登记确认时间;如若对应机构启用了库存,此时的【审核时间】将直接影响库存变化
          </div>
        </div>
        <div class="main-right">
          <el-carousel height="300px" style="margin-top: 70px;">
            <el-carousel-item v-for="item in imgList" :key="item">
              <el-image class="right-img" :src="item" :preview-src-list="imgList" />
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset">关闭</el-button>
        <el-button type="primary" @click="pass(5)">不通过</el-button>
        <el-button type="primary" @click="pass(2)">通过</el-button>
        <el-button v-if="temp.isSign === 1" type="primary" @click="showEleContact">查看电子合同</el-button>
      </div>
      <el-dialog
        width="500px"
        title="提示"
        :visible.sync="innerVisible"
        append-to-body
      >
        <p class="innerTips"> <svg-icon class="innerIcon" icon-class="warningIcon" />请填写不通过原因</p>
        <el-input v-model="noPassReason" type="textarea" :rows="3" maxlength="254" show-word-limit />
        <div slot="footer" class="dialog-footer">
          <el-button @click="innerClose">取 消</el-button>
          <el-button type="primary" @click="innerConfirm">确定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
  import { queryCashPledgeDetail, queryCashPledgeAudit, showEleContact } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'

  export default {
    name: 'depositaudit',
    props: {
      calcTypeList: {
        type: Array,
        required: true
      },
      paymentMethodList: {
        type: Array,
        required: true
      },
      payStatusList: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        baseUrl: 'http://image.haoyunqi.com.cn/',
        params: {
          atTime: ''
        },
        temp: {
          remark: ''
        },
        rules: {
          atTime: [{ required: true, message: '请选择审核时间', trigger: 'change' }]
        },
        tableData: {
          column: [
            // {
            //   prop: 'goodsCount',
            //   label: '序号',
            //   width: 60
            // },
            {
              prop: 'goodsName',
              label: '规格型号'
            },
            {
              prop: 'rental',
              label: '单个租金（元）',
              width: 130,
              render: (h, { row }) => {
                var rental = row.rental || '0.00'
                rental = (rental * 1).toFixed(2)
                return <span>{rental}</span>
              }
            },
            {
              prop: 'deposit',
              label: '单个押金(元)',
              render: (h, { row }) => {
                var deposit = row.deposit || '0.00'
                deposit = (deposit * 1).toFixed(2)
                return <span>{deposit}</span>
              }
            },
            {
              prop: 'goodsCount',
              label: '数量'
            },
            {
              prop: 'totalDeposit',
              label: '总押金(元)',
              render: (h, { row }) => {
                var totalDeposit = row.totalDeposit || '0.00'
                totalDeposit = (totalDeposit * 1).toFixed(2)
                return <span>{totalDeposit}</span>
              }
            },
            {
              prop: 'btNoIDS',
              label: '气瓶号'
            }
          ],
          data: {
            rows: []
          }
        },
        imgList: [],
        innerVisible: false,
        noPassReason: ''
      }
    },
    computed: {
      // 开始时间
      beginDt: function() {
        return this.temp.beginDt ? parseTime(this.temp.beginDt, '{y}-{m}-{d}') : ''
      },
      // 收款方式
      calcType: function() {
        return formatColumnMap(this.calcTypeList, 'value', this.temp.calcType, 'desc')
      },
      // 支付方式
      paymentMethod: function() {
        return formatColumnMap(this.paymentMethodList, 'value', this.temp.paymentMethod, 'desc')
      },
      // 支付状态
      payStatus: function() {
        return formatColumnMap(this.payStatusList, 'value', this.temp.payStatus, 'desc')
      },
      // 经办时间
      transactDt: function() {
        return this.temp.transactDt && parseTime(this.temp.transactDt, '{y}-{m}-{d} {h}:{i}:{s}')
      },
      // 手续费
      fee1: function() {
        var fee1 = this.temp.fee1 || '0.00'
        fee1 = (fee1 * 1).toFixed(2)
        return fee1
      }
    },
    created() {},
    methods: {
      async open(temp) {
        const res = await queryCashPledgeDetail({
          depCode: temp.depositCode,
          depositId: temp.depositId,
          depStatus: temp.depStatus
        })
        this.temp = res.data
        this.imgList = []
        // if (parseTime(this.temp.beginDt, '{y}-{m}-{d}') < parseTime(new Date(), '{y}-{m}-{d}')) {
        //   this.params.atTime = ''
        // } else { //产品讨论说不清空  2023-10-12
        this.params.atTime = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
        // }
        parseTime(new Date(), '{y}-{m}-{d} {h}:{i}')
        console.log('this.temp ', this.temp)
        this.tableData.data.rows = res.data.depositDetails
        this.initImg()
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      initImg() {
        if (this.temp.depositUrl) {
          this.imgList.push(this.baseUrl + this.temp.depositUrl)
        }
        for (let i = 2; i <= 6; i++) {
          if (this.temp['depositUrl' + i]) {
            this.imgList.push(this.baseUrl + this.temp['depositUrl' + i])
          }
        }
        console.log(this.imgList)
      },
      // 电子合同
      async showEleContact() {
        const res = await showEleContact({ depositCode: this.temp.depositCode })
        const url = res.data
        var m = document.createElement('a')
        m.href = url
        m.target = '_blank'
        document.body.appendChild(m)
        m.click()
      },
      async confirmReceiptStatusChange() {
        return new Promise((resolve, reject) => {
          // 单据状态【未审核】且【支付状态=已支付】且 回执状态【回执待回】条件下展示
          if (this.temp.depStatus === 1 && this.temp.payStatus === 3 && this.temp.reStatus === 2) {
            this.$confirm(`审核不通过后，回执状态变更为“无需回执”，是否确定审核不通过？`, '提示', {
              type: 'warning'
            }).then(() => {
              resolve()
            }).catch(() => {
              reject()
            })
          } else {
            resolve()
          }
        })
      },
      // 是否通过
      pass(depStatus) {
        this.$refs.dataForm.validate(async(valid) => {
          if (!valid) return
          if (Date.parse(this.params.atTime) > new Date()) {
            this.$message({
              type: 'warning',
              message: '审核时间不能大于当前系统时间'
            })
            return
          }
          if (depStatus === 5) {
            await this.confirmReceiptStatusChange()
            this.innerVisible = true
            return
          }

          this.$confirm('确认要执行操作吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async() => {
            const { status } = await queryCashPledgeAudit({
              depCode: this.temp.depositCode,
              auditDt: parseTime(this.params.atTime, '{y}-{m}-{d} {h}:{i}:{s}'),
              depStatus: depStatus,
              remark: this.temp.remark ? this.temp.remark : ''
            })
            if (status === 200) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.$emit('depUpDataTable')
              this.visible = false
            }
          })
        })
      },
      async innerConfirm() {
        if (!this.noPassReason) {
          this.$message.error('请填写不通过原因！')
          return
        }
        const { status } = await queryCashPledgeAudit({
          depCode: this.temp.depositCode,
          auditDt: parseTime(this.params.atTime, '{y}-{m}-{d} {h}:{i}:{s}'),
          depStatus: 5,
          remark: this.temp.remark ? this.temp.remark : '',
          noPassReason: this.noPassReason
        })
        if (status === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.innerClose()
          this.$emit('depUpDataTable')
          this.visible = false
        }
      },
      innerClose() {
        this.noPassReason = ''
        this.innerVisible = false
      },
      // 合计方法
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '押金合计'
            return
          }
          if ([1, 3, 4, 5].includes(index)) {
            sums[index] = ''
            return
          }

          const values = data.map((item) => Number(item[column.property]))
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        })
        return sums
      },
      // 关闭
      reset() {
        this.params.atTime = ''
        this.temp.remark = ''
        this.visible = false
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}
.dialog-main {
  display: flex;
  justify-content: space-between;
  width: 100%;
  .main-left {
    width: 55%;
  }
  .main-right {
    width: 44%;
    .right-img {
      height: 300px;
    }
  }
}

.innerTips {
  margin-bottom: 10px;
  .innerIcon {
    margin-right: 4px;
  }
}
</style>
